# Contributor: Will Sinatra <wpsinatra@gmail.com>
# Maintainer: Will Sinatra <wpsinatra@gmail.com>
pkgname=fennel
pkgver=1.4.2
pkgrel=0
pkgdesc="A Lua Lisp Language"
url="https://fennel-lang.org"
arch="all" #detects noarch, but contains compiled binaries
license="MIT"
subpackages="$pkgname-doc"
source="fennel-$pkgver.tar.gz::https://git.sr.ht/~technomancy/fennel/archive/$pkgver.tar.gz"
replaces="fennel"
options="net"

case "$CARCH" in
ppc64le|s390x|riscv64|loongarch64) _lua_versions="5.1 5.2 5.3 5.4" ;;
*) _lua_versions="5.1 5.2 5.3 5.4 jit" ;;
esac

for _v in $_lua_versions; do
	makedepends="$makedepends lua$_v-dev"

	subpackages="$subpackages $pkgname$_v:_subpackage"
done

prepare() {
	default_prepare

	for _v in $_lua_versions; do
		cp -r "$builddir" "$builddir-$_v"
	done
}

build() {
	for _v in $_lua_versions; do
		msg "Building for lua$_v..."
		cd "$builddir-$_v"

		if [ $_v = "5.1" ]; then
			 libdir=/usr/lib/liblua.so
			 includedir=/usr/include
		elif [ $_v = "jit" ]; then
			 libdir=/usr/lib/libluajit-5.1.so
			 includedir=/usr/include/luajit-2.1
		else
			libdir=/usr/lib/lua$_v/liblua.so
			includedir=/usr/include/lua$_v
		fi

		make fennel.lua \
			 COMPILE_ARGS="FENNEL_PATH=src/?.fnl FENNEL_MACRO_PATH=src/?.fnl CC_OPTS=" \
			 fennel-bin \
			 LUA=lua$_v \
			 NATIVE_LUA_LIB=$libdir \
			 BIN_LUA_VERSION=$_v \
			 LUA_INCLUDE_DIR=$includedir \
			 BIN_LUA_DIR=/usr/bin/lua$_v

		./fennel-bin --compile src/fennel/binary.fnl > binary.lua
	done
}

check() {
	for _v in $_lua_versions; do
		msg "Testing for lua$_v..."
		cd "$builddir-$_v"

		make test LUA=lua$_v
	done
}

package() {
	cd "$builddir-5.4"
	gzip -9n man/man1/fennel.1
	gzip -9n man/man3/fennel-api.3
	gzip -9n man/man5/fennel-reference.5
	gzip -9n man/man7/fennel-tutorial.7

	install -Dm644 man/man1/fennel.1.gz \
			-t "$pkgdir"/usr/share/man/man1/
	install -Dm644 man/man3/fennel-api.3.gz \
			-t "$pkgdir"/usr/share/man/man3/
	install -Dm644 man/man5/fennel-reference.5.gz \
			-t "$pkgdir"/usr/share/man/man5/
	install -Dm644 man/man7/fennel-tutorial.7.gz \
			-t "$pkgdir"/usr/share/man/man7/

}

_subpackage() {
	local _v="${subpkgname#"$pkgname"}"
	pkgdesc="A Lua Lisp Language for Lua $_v"
	install_if="lua$_v $pkgname=$pkgver-r$pkgrel"
	depends="$depends lua$_v"

	cd "$builddir-$_v"

	install -Dm0644 "fennel.lua" \
			-t "$subpkgdir/usr/share/lua/$_v/"

	install -Dm0644 "binary.lua" \
			-t "$subpkgdir/usr/share/lua/$_v/fennel/"

	install -Dm0755 "fennel-bin" \
			"$subpkgdir/usr/bin/fennel$_v"
}

sha512sums="
13b6020314d010566c7521b85065a446e09f8a0cfec9b9cb4bc2e23fe59369d105538bcb8a3a7cd865c399742d98a1742da932f8bde993c1136422f803069071  fennel-1.4.2.tar.gz
"
